package com.lpf.xypermission.aspectj;

import android.content.Context;
import android.util.Log;

import com.lpf.xypermission.activity.RequestPermissionActivity;
import com.lpf.xypermission.annotation.PermissionCanceled;
import com.lpf.xypermission.annotation.PermissionDenied;
import com.lpf.xypermission.annotation.PermissionNeed;
import com.lpf.xypermission.util.ApplicationUtil;
import com.lpf.xypermission.util.PermissionUtil;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * Created by lpf on 2022/6/7 0007
 * Describe:
 */

@Aspect
public class PermissionAspect {


    private String tag = "lpf";

    @Pointcut("execution(@com.lpf.xypermission.annotation.PermissionNeed * *(..)) && @annotation(permission)")
    public void requestPermission(PermissionNeed permission) {


    }

    @Around("requestPermission(permission)")
    public void aroundJPoint(ProceedingJoinPoint joinPoint, PermissionNeed permission) {

        Object aThis = joinPoint.getThis();

        Context context = ApplicationUtil.getApplication();

        String[] permissions = permission.permissions();
        int requestCode = permission.requestCode();

        Log.e(tag, "aroundJPoint>>>>>" + permissions.toString() + ">>>>>>" + requestCode);

        RequestPermissionActivity.startPermissionRequest(context, permissions, requestCode, new Ipermission() {
            @Override
            public void onPermissionGranted() {
                try {
                    joinPoint.proceed();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }

            @Override
            public void onPermissionCanceled(int requestCode) {

                PermissionUtil.invokeAnnotation(aThis, PermissionCanceled.class, requestCode);

            }

            @Override
            public void onPermissionDenied(int requestCode) {

                PermissionUtil.invokeAnnotation(aThis, PermissionDenied.class, requestCode);

            }
        });


    }


}
